import {reqCartList,reqDeleteCartById,reqUpdateCheckedById} from '@/api/index'
const actions ={
   async getCartList(context){
      let result= await reqCartList()
      if(result.code==200){
        context.commit('GETCARTLIST',result.data)
      }
    },
    async deleteCartListBySkuId(context,skuId){
        let result = await reqDeleteCartById(skuId);
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
  async  UpdateCheckedById(context,{skuId,isChecked}){
      let result= await reqUpdateCheckedById(skuId,isChecked)
      if(result.code==200){
        return 'ok'
      }else{
        return Promise.reject(new Error('faile'))
      }
    },
    deleteAllCheckedCart(context){
        let PromiseAll=[];
        context.getters.cartList.cartInfoList.forEach((item)=>{
            let promise=item.isChecked==1?context.dispatch('deleteCartListBySkuId',item.skuId):'';
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },
    
    updateAllCartChecked(context,isChecked){
       let promiseAll=[];
       context.state.cartList[0].cartInfoList.forEach((item)=>{
       let promise = context.dispatch('UpdateCheckedById',{
        skuId:item.skuId,
        isChecked,
       })
       promiseAll.push(promise); 
       })
       return Promise.all(promiseAll)
    }
}
const mutations={
    GETCARTLIST(state,cartList){
       state.cartList=cartList
    }
}
const state = {
    cartList:[]
}
const getters ={
   cartList(state){
    return state.cartList[0] || {}
   }    
}
export default {
    actions,mutations,state,getters
}